package edu.lingnan.rili.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.lingnan.rili.mapper.UploadingMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.lingnan.rili.mapper.MatchMapper;
import edu.lingnan.rili.mapper.UploadingMapper;
import edu.lingnan.rili.pojo.Awarded;
import edu.lingnan.rili.mapper.AwardedMapper;
import edu.lingnan.rili.pojo.Uploading;
import edu.lingnan.rili.pojo.Match;
import edu.lingnan.rili.pojo.Uploading;
import edu.lingnan.rili.service.AwardedService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.lingnan.rili.service.UploadingService;
import edu.lingnan.rili.vo.AwardedVo;
import edu.lingnan.rili.vo.PagingQueryResult;
import edu.lingnan.rili.vo.UploadingVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import edu.lingnan.rili.utils.Result;
import edu.lingnan.rili.utils.ScheduledData;
import edu.lingnan.rili.vo.PagingQuery;
import edu.lingnan.rili.vo.PagingQueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 陈世杰
 * @since 2022-01-23
 */
@Service
public class AwardedServiceImpl extends ServiceImpl<AwardedMapper, Awarded> implements AwardedService {

    @Autowired
    private AwardedMapper awardedMapper;

    @Autowired
    private UploadingService uploadingService;

    @Autowired
    private UploadingMapper uploadingMapper;

    @Autowired
    private ScheduledData scheduledData;

    @Resource
    private MatchMapper matchMapper;

    @Override
    public List<Awarded> selectAllAnnounced() {
        QueryWrapper<Awarded> wrapper = new QueryWrapper<>();
        wrapper.select(Awarded.class, item -> !"uploading".equals(item.getColumn()));
        wrapper.eq("pubblicity_type", 1);
        List<Awarded> awardedList = awardedMapper.selectList(wrapper);

        // 查询加分数据
        if (!ObjectUtils.isEmpty(awardedList)) {
            return awardedList;
        }
        return null;
    }

    @Override
    public List<AwardedVo> selectByAnnounced() {
        //创建一个QueryWrapper的对象
        QueryWrapper<Awarded> wrapper = new QueryWrapper<>();
        // 查询uploading之外的字段
        wrapper.select(Awarded.class, item -> !"uploading".equals(item.getColumn()));
        // 查询已公示的数据
        wrapper.eq("pubblicity_type", 1);

        List<Awarded> awardedList = awardedMapper.selectList(wrapper);

        ArrayList<AwardedVo> awardedVos = new ArrayList<>();

        // 查询加分数据
        if (!ObjectUtils.isEmpty(awardedList)) {
            for (Awarded awarded : awardedList) {
                AwardedVo awardedVo = new AwardedVo();
                BeanUtils.copyProperties(awarded, awardedVo);
                UploadingVo uploading = uploadingService.selectById(awarded.getUploadingId(), Uploading.EXAMINATION_PASSED);
                System.out.println(uploading);
                if (uploading != null && !ObjectUtils.isEmpty(uploading)) {
                    BeanUtils.copyProperties(uploading, awardedVo);
                    awardedVos.add(awardedVo);
                }
            }
        }
        return awardedVos;
    }

    @Override
    public PagingQueryResult<AwardedVo> selectByAnnouncedAndPage(int currentPage, int pageSize) {
        //创建一个QueryWrapper的对象
        QueryWrapper<Awarded> wrapper = new QueryWrapper<>();
        // 查询uploading之外的字段
        wrapper.select(Awarded.class, item -> !"uploading".equals(item.getColumn()));
        // 查询已公示的数据
        wrapper.eq("pubblicity_type", 1);

        PagingQueryResult<AwardedVo> pageResult = new PagingQueryResult<>();

        // 分页查询
        Page<Awarded> awardedPage = awardedMapper.selectPage(new Page<Awarded>(currentPage, pageSize), wrapper);

        pageResult.setPageTotal((int) awardedPage.getTotal());
        pageResult.setRows(awardedPage.getRecords().size());

        // 获取分页数据
        List<Awarded> awardedList = awardedPage.getRecords();
        ArrayList<AwardedVo> awardedVos = new ArrayList<>();

        // 查询加分数据
        if (!ObjectUtils.isEmpty(awardedList)) {
            for (Awarded awarded : awardedList) {
                AwardedVo awardedVo = new AwardedVo();
                BeanUtils.copyProperties(awarded, awardedVo);
                UploadingVo uploading = uploadingService.selectById(awarded.getUploadingId(), Uploading.EXAMINATION_PASSED);
                System.out.println(uploading);
                if (uploading != null && !ObjectUtils.isEmpty(uploading)) {
                    BeanUtils.copyProperties(uploading, awardedVo);
                    awardedVos.add(awardedVo);
                }
            }
            pageResult.setDataList(awardedVos);
        }
        return pageResult;
    }

    @Override
    public List<AwardedVo> selectAllNotReviewed() {
        List<Object> uploadingIds = uploadingService.getUploadingIdNotReviewed();
        if (uploadingIds == null) {
            return null;
        }
        QueryWrapper<Awarded> wrapper = new QueryWrapper<>();
        wrapper.in("uploading_id", uploadingIds);

        List<Awarded> awardedList = awardedMapper.selectList(wrapper);

        ArrayList<AwardedVo> awardedVos = new ArrayList<>();

        // 查询加分数据
        if (!ObjectUtils.isEmpty(awardedList)) {
            for (Awarded awarded : awardedList) {
                AwardedVo awardedVo = new AwardedVo();
                BeanUtils.copyProperties(awarded, awardedVo);
                UploadingVo uploading = uploadingService.selectById(awarded.getUploadingId(), Uploading.PENDING_REVIEW);
                System.out.println(uploading);
                if (uploading != null && !ObjectUtils.isEmpty(uploading)) {
                    BeanUtils.copyProperties(uploading, awardedVo);
                    awardedVos.add(awardedVo);
                }
            }
        }

        return awardedVos;
    }

    @Override
    public PagingQueryResult<AwardedVo> selectAllNotReviewedByPage(int currentPage, int pageSize) {
        List<Object> uploadingIds = uploadingService.getUploadingIdNotReviewed();
        if (uploadingIds == null) {
            return null;
        }
        QueryWrapper<Awarded> wrapper = new QueryWrapper<>();
        wrapper.in("uploading_id", uploadingIds);

        PagingQueryResult<AwardedVo> pageResult = new PagingQueryResult<>();

        // 分页查询
        Page<Awarded> awardedPage = awardedMapper.selectPage(new Page<>(currentPage, pageSize), wrapper);
        // 获取查询结果中的数据
        List<Awarded> awardedList = awardedPage.getRecords();
        // 设置返回对象属性
        pageResult.setPageTotal((int) awardedPage.getTotal());
        pageResult.setRows(awardedList.size());


        ArrayList<AwardedVo> awardedVos = new ArrayList<>();

        // 查询加分数据
        if (!ObjectUtils.isEmpty(awardedList)) {
            for (Awarded awarded : awardedList) {
                AwardedVo awardedVo = new AwardedVo();
                BeanUtils.copyProperties(awarded, awardedVo);
                UploadingVo uploading = uploadingService.selectById(awarded.getUploadingId(), Uploading.PENDING_REVIEW);
                System.out.println(uploading);
                if (uploading != null && !ObjectUtils.isEmpty(uploading)) {
                    BeanUtils.copyProperties(uploading, awardedVo);
                    awardedVos.add(awardedVo);
                }
            }
            pageResult.setDataList(awardedVos);
        }

        return pageResult;
    }

    @Override
    public Boolean audit(String uploadingId, String stateId, String stateCause) {
        Uploading uploading = uploadingMapper.selectById(uploadingId);
        if (!ObjectUtils.isEmpty(uploading)) {
            if (stateId.equals(Uploading.DISMISSED)) {
                // 驳回情况
                uploading.setStateCause(stateCause);
                uploading.setStateId(stateId);
            } else if (stateId.equals(Uploading.EXAMINATION_PASSED)) {
                // 审核通过情况
                uploading.setStateId(Uploading.EXAMINATION_PASSED);
            }
            int row = uploadingMapper.updateById(uploading);
            return row > 0;
        }
        return false;
    }

    /**
     * 这是一个其他比赛公示分页查询的方法
     * （公示出来的为审核通过的名单，state-id=1）
     *
     * @param page 查询的页数（第几页）
     * @param rows 一页显示的信息条数
     * @return
     */

    @Override
    public Result<PagingQueryResult<PagingQuery>> publicityOfOtherCompetitions(int page, int rows) {
        //获取总记录条数信息(uploading表中state-id=1&&uploading-type=0)
        QueryWrapper<Uploading> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uploading_type", scheduledData.getUploadingTypeOtherGames())
                .eq("state_id", scheduledData.getStateIdAdopt());
        Integer totalRows = uploadingMapper.selectCount(queryWrapper);
        System.out.println("测试其他比赛公示数据条数：" + totalRows);

        //根据一页的信息数算出总页数
        int pages = totalRows / rows ;
        if (totalRows % rows != 0)
            pages = pages + 1;
        System.out.println("测试总页数为：" + pages);

        //根据参数page（第几页）获取该页的数据,从第几条数据开始算起，算到第几条数据
        int startNum = (page - 1) * rows;//从第几条数据开始算起
        System.out.println("测试从第几条数据开始算起，到第几条数据截至：" + startNum + ";" + rows);
        //在uploading表中获取信息
        System.out.println("========================================================");
        List<Uploading> uploadingInfos = uploadingMapper.getOtherGamesUploadingInfos(startNum, rows);
        //判断是否为空，若为空则返回空result(查询不到数据的时候需要用到)
        if (uploadingInfos.size() == 0) {
            Result result = new Result(204, "查询的数据为空");
            return result;
        }
        System.out.println("uploadingInfos的长度："+uploadingInfos.size());
        List<PagingQuery> list = new ArrayList<>();//存储初步处理过的数据
        //将两表中获取的数据整合到PagingQuery对象中
        try {
            for (Uploading uploading : uploadingInfos) {
                PagingQuery pagingQuery = new PagingQuery();
                String uploadingId = uploading.getUploadingId();//通过uploadingId与awarded表联系
                QueryWrapper<Awarded> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("uploading_id", uploadingId);
                Awarded awarded = awardedMapper.selectOne(queryWrapper1);
                int w;
                if (awarded == null) {
                    continue;
                }
                String usersId = uploading.getUsersId();//通过usersId与match表联系
                QueryWrapper<Match> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("users_id", usersId);
                Match match = matchMapper.selectOne(queryWrapper2);
                pagingQuery.setUserClass(match.getUserClass()).setUserGrade(match.getUserGrade())
                        .setUserMajor(match.getUserMajor()).setUsersName(match.getUsersName())
                        .setScore(awarded.getScore()).setAddtype(awarded.getAddtype())
                        .setGameName(uploading.getGameName()).setUsersId(usersId);
                list.add(pagingQuery);
            }
        } catch (NullPointerException e) {
            log.error("空指针错误");
        }
        System.out.println("ooooooooooooooooooooo" + list);
        //将总数据条数，总页数，该页的查询到的数据等等信息封装到PagingQueryResult中去
        PagingQueryResult<PagingQuery> pagingQueryPagingQueryResult = new PagingQueryResult<>();
        pagingQueryPagingQueryResult.setDataList(list);
        pagingQueryPagingQueryResult.setPageTotal(pages);
        pagingQueryPagingQueryResult.setRows(totalRows);
        Result<PagingQueryResult<PagingQuery>> result = new Result<>(200, "查询成功！");
        result.setData(pagingQueryPagingQueryResult);

        return result;

    }

    /**
     * 这是一个其他加分公示分页查询的方法
     *
     * @param page 查询的页数（第几页）
     * @param rows 一页显示的信息条数
     * @return
     */
    @Override
    public Result<PagingQueryResult<PagingQuery>> publicityOfExtraPoints(int page, int rows) {
        //获取总记录条数信息(uploading表中state-id=1&&uploading-type=0)
        QueryWrapper<Uploading> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uploading_type", scheduledData.getUploadingTypeOtherBonusPoints())
                .eq("state_id", scheduledData.getStateIdAdopt());
        Integer totalRows = uploadingMapper.selectCount(queryWrapper);
        System.out.println("测试其他比赛公示数据条数：" + totalRows);

        //根据一页的信息数算出总页数
        int pages = totalRows / rows;
        if (totalRows % rows != 0)
            pages = pages + 1;
        System.out.println("测试总页数为：" + pages);

        //根据参数page（第几页）获取该页的数据,从第几条数据开始算起，算到第几条数据
        int startNum = (page - 1) * rows;//从第几条数据开始算起
        System.out.println("测试从第几条数据开始算起，到第几条数据截至：" + startNum + ";" + rows);
        //在uploading表中获取信息
        System.out.println("测试获取到的数据：");
        List<Uploading> uploadingInfos = uploadingMapper.getOtherPointsUploadingInfos(startNum, rows);
        //判断是否为空，若为空则返回空result(查询不到数据的时候需要用到)
        if (uploadingInfos.size() == 0) {
            Result result = new Result(203, "查询的数据为空");
            return result;
        }
        List<PagingQuery> list = new ArrayList<>();//存储初步处理过的数据
        //将两表中获取的数据整合到PagingQuery对象中
        try {
            for (Uploading uploading : uploadingInfos) {
                PagingQuery pagingQuery = new PagingQuery();
                String uploadingId = uploading.getUploadingId();//通过uploadingId与awarded表联系
                QueryWrapper<Awarded> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("uploading_id", uploadingId);
                Awarded awarded = awardedMapper.selectOne(queryWrapper1);
                if (awarded == null) {
                    continue;
                }
                String usersId = uploading.getUsersId();//通过usersId与match表联系
                QueryWrapper<Match> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("users_id", usersId);
                Match match = matchMapper.selectOne(queryWrapper2);
                pagingQuery.setUserClass(match.getUserClass()).setUserGrade(match.getUserGrade())
                        .setUserMajor(match.getUserMajor()).setUsersName(match.getUsersName())
                        .setScore(awarded.getScore()).setAddtype(awarded.getAddtype())
                        .setGameName(uploading.getGameName()).setUsersId(usersId);
                list.add(pagingQuery);
            }
        } catch (NullPointerException e) {
            log.error("空指针错误");
            Result result = new Result(204, "无内容");
            return result;
        }
        //将总数据条数，总页数，该页的查询到的数据等等信息封装到PagingQueryResult中去
        PagingQueryResult<PagingQuery> pagingQueryPagingQueryResult = new PagingQueryResult<>();
        pagingQueryPagingQueryResult.setDataList(list);
        pagingQueryPagingQueryResult.setPageTotal(pages);
        pagingQueryPagingQueryResult.setRows(totalRows);
        Result<PagingQueryResult<PagingQuery>> result = new Result<>(200, "查询成功！");
        result.setData(pagingQueryPagingQueryResult);

        return result;

    }

    /**
     * 这是一个其他比赛公示页面的模糊查询
     *
     * @param keywords 关键字
     * @return
     */
    @Override
    public Result<PagingQueryResult<PagingQuery>> queryOfOtherCompetitionPublicityKeywords
    (String keywords, int page, int rows) {

        if ("".equals(keywords) || keywords == null) {
            Result result = new Result(201, "请输入查询字段");
            return result;
        }
        //通过keywords从数据库中获取数据（通过嵌套查询）
        List<PagingQuery> list = uploadingMapper.fuzzyQueryOfOtherCompetitionPublicityPages(keywords);
        if (list.size() == 0) {
            Result result = new Result(204, "没有数据！");
            return result;
        }
        //处理获取到的数据
        int totalRows = list.size();
        int pages = totalRows / rows;
        if (totalRows % rows != 0)
            pages = pages + 1;
        int startRow = (page - 1) * rows;
        int endRow = startRow + rows;
        List<PagingQuery> list1;
        //需要进行判断，有没有endRow这一行数据
        if (endRow < totalRows)
            list1 = list.subList(startRow, endRow);
        else
            list1 = list.subList(startRow, totalRows);
        System.out.println("88888888888888888888888" + list1);
        System.out.println("查询到的数据条数:" + totalRows);
        System.out.println(list);
        PagingQueryResult<PagingQuery> pagingQueryPagingQueryResult = new PagingQueryResult<>();
        pagingQueryPagingQueryResult.setDataList(list1);
        pagingQueryPagingQueryResult.setPageTotal(pages);
        pagingQueryPagingQueryResult.setRows(totalRows);
        Result<PagingQueryResult<PagingQuery>> result = new Result<>(200, "查询成功！");
        result.setData(pagingQueryPagingQueryResult);
        //返回数据
        return result;
    }

    /**
     * 这是一个其他加分公示页面的模糊查询
     *
     * @param keywords 关键字
     * @return
     */
    @Override
    public Result<PagingQueryResult<PagingQuery>> fuzzyQueryOfOtherBonusPublicityPages(String keywords, int page, int rows) {

        if ("".equals(keywords) || keywords == null) {
            Result result = new Result(201, "请输入查询字段");
            return result;
        }
        //通过keywords从数据库中获取数据（通过嵌套查询）
        List<PagingQuery> list = uploadingMapper.fuzzyQueryOfOtherBonusPublicityPages(keywords);
        if (list.size() == 0) {
            Result result = new Result(204, "没有数据！");
            return result;
        }
        //处理获取到的数据
        int totalRows = list.size();
        int pages = totalRows / rows;
        if (totalRows % rows != 0)
            pages = pages + 1;
        int startRow = (page - 1) * rows;
        int endRow = startRow + rows;
        List<PagingQuery> list1;
        //需要进行判断，有没有endRow这一行数据
        if (endRow < totalRows)
            list1 = list.subList(startRow, endRow);
        else
            list1 = list.subList(startRow, totalRows);
        System.out.println("88888888888888888888888" + list1);
        System.out.println("查询到的数据条数:" + totalRows);
        System.out.println(list);
        PagingQueryResult<PagingQuery> pagingQueryPagingQueryResult = new PagingQueryResult<>();
        pagingQueryPagingQueryResult.setDataList(list1);
        pagingQueryPagingQueryResult.setPageTotal(pages);
        pagingQueryPagingQueryResult.setRows(totalRows);
        Result<PagingQueryResult<PagingQuery>> result = new Result<>(200, "查询成功！");
        result.setData(pagingQueryPagingQueryResult);
        //返回数据
        return result;
    }
}
